#pragma once
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<assert.h>
#include<regex.h>
#include"TcpServer.hpp"

#define DEFALT_TIMEOUT 10

std::unordered_map<int, std::string> _statu_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};

//需要实现四个类，Util HttpResponse HttpRequest HttpServer

class Util//工具类
{
public:
    //分割字符串函数
    static size_t Split(const std::string& src ,const std::string& sep ,std::vector<std::string>& array)
    {
        //将分割得到的字符串放进数组array 中
        ssize_t offset = 0;
        while(offset < src.size())
        {
            ssize_t pos = src.find(sep.c_str());
            if(pos == std::string::npos)
            {
                //没有找到就将offset 到最后的字符串继续加入
                if(pos == src.size()) break;
                array.push_back(src.substr(offset));
                return array.size();
            }
            //找到了就截取字符串放入
            if(pos == offset)
            {
                //表示两个分割符相邻
                offset = pos + sep.size();//越过后面一个分隔符
                continue;//没有内容不放入array 中
            }
            array.push_back(src.substr(offset , pos - offset));
            //移动offset
            offset += sep.size();
        }
        return array.size();
    }

    //读取文件中的所有内容，将读取到的内容放到字符串 中
    static bool ReadFile(const std::string& filename , std::string* buf)
    {
        //利用ifstream
        std::ifstream ifs(filename ,std::ios::binary);//以二进制的形式打开文件
        //判断文件是否打开成功
        if(!ifs.is_open())
        {
            std::cout << "打开文件失败: " << filename << std::endl;
            return false;
        }
        //获取文件大小，移动其指针来获取
        size_t fsize = 0;
        ifs.seekg(0 , ifs.end);//跳转读写位置到结尾
        fsize = ifs.tellg();//获取文件大小
        ifs.seekg(0,ifs.beg);
        //开辟同样大小的文件
        buf->resize(fsize);
        //读取数据
        ifs.read(&(*buf)[0] , fsize);
        if(ifs.good() == false)
        {
            std::cout << "读取文件: " << filename << "失败" << std::endl;
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }

    //向文件中写入数据
    static bool WriteFile(const std::string& filename , const std::string& buf)
    {
        //打开文件
        std::ofstream ofs(filename , std::ios::binary | std::ios::app);//以二进制追加的形式打开文件
        if(!ofs.is_open())
        {
            std::cout << "打开文件失败: " << filename << std::endl;
            return false;
        }
        //调用write 进行写入并判断写入是否成功
        ofs.write(buf.c_str() , buf.size());
        if(ofs.good() == false)
        {
            std::cout << "写入文件: " << filename << "失败" << std::endl;
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }

    //URL编码
    static std::string UrlEncode(const std::string url , bool convert_space_to_plus)//是否需要将空格转换为+
    {
        std::string res;
        for(auto & c : url)
        {
            //判断是否为特殊字符，是特俗字符就将其转换为 %16进制
            if(c == '.' || c=='-' || c=='~' || isalnum(c))
            {
                res+=c;
                continue;
            }
            if(c == ' ' && convert_space_to_plus)
            {
                //将空格转换为 + 
                res+='+';
                continue;
            }
            //剩下的字符均需要进行编码
            char tmp[4] = {0};
            //利用snprintf 格式化写入tmp 中
            snprintf(tmp, 4 , "%%%02x" , c);
            res += tmp;
        }
        return res;
    }

    static char HEXTOI(char c)
    {
        if(c>='0' && c<='9') return c-'0';
        else if(c >= 'a' && c<='z') return c-'a'+10;
        else if(c >= 'A' && c<='Z') return c-'A' + 10;
    }

    //解码
    static std::string UrlDecode(const std::string url , bool convert_space_to_plis)
    {
        //遇见了%需要将其后面两个16进制数字转换为一个字符
        std::string res;
        for(int i = 0; i<url.size();i++)
        {
            //先判断是否需要处理+
            if(url[i]=='+' && convert_space_to_plis)
            {
                res += ' ';
                continue;
            }
            //处理% 问题
            if(url[i] == '%' && (i+2) < url.size())
            {
                //获取后面两个
                char v1 = HEXTOI(url[i+1]);
                char v2 = HEXTOI(url[i+2]);
                //组成一个字符
                char v = v1*16 + v2;
                res+=v;
                continue;
            }
            //普通未做处理的字符
            res += url[i];
        }
        return res;
    }

    //响应状态码的获取
    static std::string StatuDesc(int statu)
    {
        //根据statu在_statu_msg中查找
        auto it = _statu_msg.find(statu);
        if(it == _statu_msg.end()) return"UnKnown";
        return it->second; 
    }

    //根据文件名后缀获取mime
    static std::string ExtMine(const std::string& filename)
    {
        //利用rfind
        size_t pos = filename.rfind('.');
        if(pos == std::string::npos)
        {
            return "application/octet-stream";
        }
        //根据扩展名获取mime，实际上就是去_mime_msgz宏查找
        auto it = _mime_msg.find(filename.substr(pos));
        if(it == _mime_msg.end()) 
        {
            return "application/octet-stream";
        }
        return it->second;
    }
    //判断一个文件是否为目录
    static bool IsDirectory(const std::string* filename)
    {
        struct stat st;
        int ret = stat(filename->c_str() , &st);//函数stat 就是判断一个文件是否为目录的，struct stat 中可使用宏S_ISDIR 判断
        if(ret < 0)
        {
            return false;
        }
        return S_ISDIR(st.st_mode);
    }
    //判断一个文件是否为普通文件
    static bool IsRegular(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str() , &st);
        if(ret < 0)
        {
            return false;
        }
        return S_ISREG(st.st_mode);
    }

    //http 中请求资源有效性的判断
    //客户端智能访问对应根目录中的资源，其他的不予理会
    static bool VaildPath(const std::string& path)
    {
        //记录深度，一定不能是根目录的上级目录
        //分割 --> 判断深度
        std::vector<std::string> subdir;
        Split(path , "/" , subdir);
        //遍历数组
        int level = 0;
        for(auto e: subdir)
        {
            if(e=="..") 
            {
                level--;
                if(level < 0) return false;
                continue;
            }
            level++;
        }
        return true;
    }
};

//实现请求部分的模块
//请求方法 url 协议版本 \r\n
//k: v \r\n
// \r\n
//正文
class HttpRequest
{
public:
    std::string _method;//请求方法
    std::string _path;//请求资源路径，url
    std::string _version;//协议版本
    std::string _body;//正文
    std::smatch _matches;//资源路径的正则表达式提取数据
    std::unordered_map<std::string,std::string> _headers;//kv 
    std::unordered_map<std::string, std::string> _params;//查询字符串 param ：参数
public: 
    HttpRequest(){}
    //重置
    void Reset()
    {
        //该清空的清空，协议默认为 HTTP/1.1
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        //正则表达式smatch没有clear 函数利用空对象交换清空
        std::smatch match;
        match.swap(_matches);
        _headers.clear();
        _params.clear();
    }

    //插入头部字段,Kv结构的数据
    void SetHeader(const std::string& key , const std::string& val)
    {
        _headers.insert(std::make_pair(key,val));
    }
    //查询key
    bool HasHeader(const std::string& key) const 
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return false;
        }
        return true;
    }

    //获取指定头部字段的值
    std::string GetHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return "";
        }
        return it->second;
    }

    //插入查询字符串，插入_parms 中
    void SetParam(const std::string& key , const std::string& val)
    {
        _params[key] = val;
    }
    //判断是否存在某个特定的查询字符串
    bool HasParam(const std::string& key)
    {
        auto it = _params.find(key);
        if(it == _params.end())
        {
            return false;
        }
        return true;
    }
    //获取指定的查询字符串
    std::string GetParam(const std::string& key) const 
    {
        auto it = _params.find(key);
        if(it == _params.end())
        {
            return "";
        }
        return it->second;
    }

    //获取正文长度
    size_t ContentLength() const
    {
        //先判断有无正文
        bool ret = HasHeader("Content-Length");
        if(ret == false) return 0;
        std::string clen = GetHeader("Content-Length");
        return std::stoi(clen);
    }
    //判断是否为短连接
    bool Close() const
    {
        //查看KV中是否存在Connection 字段，或者字段中的值为close ,则为短连接，否则就是长连接
        // if(!HasHeader("Connection") || GetHeader("Connection")=="close") return true;
        // return false;

        if(HasHeader("Connection") == true && GetHeader("Connection")=="keep-alive") return false;
        return true;
    }
    ~HttpRequest(){}
};

//应答类
class HttpResponce
{
public:
    int _statu;//状态码
    bool _redirect_flag;//重定向标志
    std::string _body;//正文
    std::string _redirect_url;//重定向到了哪里
    std::unordered_map<std::string , std::string> _headers;
public:
    HttpResponce(int statu = 100)
    :_statu(statu)
    ,_redirect_flag(false)
    {}
    //重置
    void Reset()
    {
        _statu = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }
    //插入头部字段- kv
    void SetHeader(const std::string& key , const std::string& val)
    {
        _headers[key] = val;
    }
    //判断某个头部字段是否存在
    bool HasHeader(const std::string& key)
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return false;
        }
        return true;
    }
    //获取头部字段的数据
    std::string GetHeader(const std::string& key)
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return "";
        }
        return it->second;     
    }
    //设置正文
    void SetContent(const std::string& body , const std::string& type ="text/html")
    {
        _body = body;
        SetHeader("Content-Type", type);
    }
    //设置重定向资源
    void SetRedirect(const std::string& url , int statu = 302)
    {
        _statu = statu;
        _redirect_flag = true;
        _redirect_url = url;
    }
    //判断是否为短连接
    bool Close()
    {
        if(HasHeader("Connection")==true && GetHeader("Connection")=="keep-alive") return false;
        return true;
    }
    ~HttpResponce(){}
};

//标记请求的接受、处理阶段的标志
typedef enum{
    RECV_HTTP_ERROR, //没有接收到，接受错误
    RECV_HTTP_LINE, //处理首行
    RECV_HTTP_HEAD, //处理kv部分
    RECV_HTTP_BODY,//处理正文
    RECV_HTTP_OVER//处理结束
}HttpRecvStatu;

//请求接受上下文的HttpContext
#define MAX_LINE 8192
class HttpContext
{
private:
    int _resp_statu;//响应状态码
    HttpRecvStatu _recv_statu;//当前接受解析的状态
    HttpRequest _request;//已经解析得到的请求信息
private:
    //解析报头首行
    bool ParseHttpLine(const std::string& line)
    {   
        //正则表达式
        std::smatch matches;
        //忽略大小写：std::regex__icase ， HTTP本身是忽略大小写的
        //书写正则表达式
        std::regex e("(GET|POST|HEAD|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01](?:\n|\r\n))?");
        bool ret = std::regex_match(line , matches , e);
        if(ret == false)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400;
            return false;
        }

        // GET /zjx/login?user=zhangsan&pass=123456 HTTP/1.1
        // k: v
        //空行
        //正文
        //从正则表达式中获取请求首行的各个数据并放入HttpRequest所对应的对象中
        _request._method = matches[1];
        //转换为大写，利用接口transform 或者 toepper,通过迭代器对容器中的数据进行操作
        std::transform(_request._method.begin() , _request._method.end() , _request._method.begin() , ::toupper);
        //请求资源路径的获取 --》 需要进行解码
        _request._path = Util::UrlDecode(matches[2] , false);
        //协议版本的获取
        _request._version = matches[4];
        //查询字符串的处理,user=zhangsan&pass=123456
        //以&作为分割，获取用户与密码
        std::vector<std::string> query_string_array;
        std::string query_string = matches[3];
        Util::Split(query_string , "&" ,query_string_array);
        //从数组中获取数据放入请求的 _params中
        //再以=作为分割分贝得到信息的key 与vlue
        for(auto& str : query_string_array)
        {
            size_t pos = str.find("=");
            if(pos == std::string::npos)
            {
                //处理细节+返回false
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 400;
                return false;
            }
            //找到了，解码构建kv放入_params中
            std::string key = Util::UrlDecode(str.substr(0 ,pos) , false);
            std::string value = Util::UrlDecode(str.substr(pos) , false);
            _request.SetParam(key,value);
        }
        return true;
    }
    //读取首行
    bool RecvHttpLine(Buffer* buf)
    {   
        if(_recv_statu != RECV_HTTP_LINE) return false;
        //获取一行的数据
        std::string line = buf->GetLineAndPop();
        //可能并没有读取到数据需要进行判断
        if(line.size()==0)
        {
            //缓冲区中的数据没有一行，首先判断缓冲区中的可读数据长度
            if(buf->ReadAbleSize() > MAX_LINE)
            {
                //存在问题
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;//url太长了
                return false;
            }
            //这才是缓冲区中的数据不足一行，等待新数据到来便可
            return true;
        }
        //判断获取到的一行的长度，如果超过了最长能处理的长度，是错误的数据宁愿不处理；处理状态+返回false
        if(line.size() > MAX_LINE)
        {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;//url太长了
                return false;           
        }
        //将获取到的数据直接去解析并设置
        bool ret = ParseHttpLine(line);
        if(ret == false) return false;
        _recv_statu = RECV_HTTP_HEAD;//进入正文处理阶段
        return true;
    }

    //读取报头中的kv部分
    bool RecvHttpHead(Buffer* buf)
    {
        //首先确认状态是否正确
        if(_recv_statu != RECV_HTTP_HEAD ) return false;
        //一行一行地取出数据
        while(1)
        {
            std::string line = buf->GetLineAndPop();
            //需要判断是否拿去到了数据
            if(line.size()==0)
            {
                //判断缓冲区是否有数据，如果有数据还没拿到数据就有问题
                if(buf->ReadAbleSize() > MAX_LINE) 
                {
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414;//url太长了
                    return false;   
                }
                //缓冲区中没有数据，等待数据到来就可以了
                return true;
            }
            //获取到了一行的数据，需要判断这一行数据是否太长了
            if(line.size() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;//url太长了
                return false;           
            }
            //对这一行的数据进行解析
            bool ret = ParseHttpHead(line);
            if(ret == false) return false;
            //修改状态
            _recv_statu = RECV_HTTP_BODY;
            return true;
        }
    }
    //解析报头中的kv部分
    bool ParseHttpHead( std::string& line)
    {
        //先解决末尾的换行符
        if(line.back() =='\n') line.pop_back();
        if(line.back() =='\r') line.pop_back();

        size_t pos = line.find(": ");
        if(pos == std::string::npos) 
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400;//Bad Request 请求报文语法/参数错误
            return false;    
        }
        std::string key = line.substr(0 ,pos);
        std::string value = line.substr(pos);
        _request.SetHeader(key , value);
        return true;
    }

    //获取正文部分
    bool RecvHttpBody(Buffer* buf)
    {
        if(_recv_statu != RECV_HTTP_BODY) return false;
        //判断是否存在正文
        size_t content_lengeth = _request.ContentLength();
        if(content_lengeth==0)
        {
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        //存在正文就需要将正文获取出来,查看往_body中已经放了多少数据
        size_t real_len = content_lengeth - _request._body.size();
        //缓冲区中的数据比real_len 长就继续获取
        if(buf->ReadAbleSize() > real_len)
        {
            _request._body.append(buf->ReadPostion() , real_len);
            buf->MoveReadOffset(real_len);
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        //缓冲区没有那么多数据,能取多少取多少然后等待数据的到来
        _request._body.append(buf->ReadPostion() , buf->ReadAbleSize());
        buf->MoveReadOffset(buf->ReadAbleSize());
        return true;
    }

public:
    HttpContext()
    :_resp_statu(200)
    ,_recv_statu(RECV_HTTP_LINE)
    {}
    //重置
    void ReSet()
    {
        _resp_statu = 200;
        _recv_statu = RECV_HTTP_LINE;
        _request.Reset();
    }
    //获取响应状态码
    int RespStatu(){ return _resp_statu;}
    //获取接受状态
    HttpRecvStatu RecvStatu(){return _recv_statu;}
    //获取请求信息
    HttpRequest & Request() { return _request;}
    //接受并接续Http请求
    void RecvHttpRequest(Buffer* buf)
    {
        //让其处于不同的状态去做不同的事情
        switch(_recv_statu)
        {
            case RECV_HTTP_LINE: RecvHttpLine(buf);
            case RECV_HTTP_HEAD: RecvHttpHead(buf);
            case RECV_HTTP_BODY:RecvHttpBody(buf);
        }
        return;
    }
    ~HttpContext(){}
}; 

//httpserver  模块实现，设计请求路由表，表中记录了针对哪一个请求需要去调用什么样的函数
//这样做，用户仅仅只需要实现业务处理函数。将请求与处理函数的映射关系，添加到服务器当中
//而服务器只需要接受请求然后根据路由器表去查找对应的函数，然后执行
//获取请求，处理请求，构建应答
class HttpServer
{
private:
    //各个方法的路由表
    using Handler = std::function<void(const HttpRequest& , HttpResponce*)>;
    //直接让正则表达式作为key值保存，因为正则表达式在编译的过程中也是有消耗的
    using Handlers  =std::vector<std::pair<std::regex , Handler>>;
    // std::unordered_map<std::string , Handler> _get_route;
    // std::unordered_map<std::string, Handler> _post_route;
    // std::unordered_map<std::string, Handler> _put_route;
    // std::unordered_map<std::string, Handler> _delete_route;
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _basedir;//静态资源根目录
    TcpServer _server;//底层基于Tcp服务器
private:    
    //请求资源错误就展示一个错误页面
    void ErrorHandler(const HttpRequest& req, HttpResponce* resp)
    {
        std::string html404 = "<!DOCTYPE html><html><head><title>404</title><style>body\
        {display:flex;height:100vh;margin:0;justify-content:center;align-items:center;\
        font-family:sans-serif;font-size:10vw;font-weight:bold}</style></head><body>404</body></html>";

        //返回应答，其实就是将404页面的内容放入应答的正文当中
        resp->SetContent(html404, "test/html");
    }
    //构建应答并发送
    void WriteResponce(const PtrConnection& conn , const HttpRequest& req, HttpResponce& resp)
    {
        //完善应答的头部字段
        if(req.Close() == true)//观察请求为长连接还是短连接
        {
            resp.SetHeader("Connection" , "close");
        }
        else{
            resp.SetHeader("Connection" , "close");
        }

        //判断正文是否为空，不为空就需要设置Content-Length 与 Content-Type
        if(resp._body.empty() == false && resp.HasHeader("Content-Length") == false)
        {
            //设置
            resp.SetHeader("Content-Length",std::to_string(resp._body.size()));
        }
        if(resp._body.empty() == false && resp.HasHeader("Content-Type") == false)
        {
            resp.SetHeader("Content-Type" , "application/octet-stream");
        }
        //设置重定向,如果重定向标志位true 就进行设置
        if(resp._redirect_flag == true)
        {
            resp.SetHeader("Location" , resp._redirect_url);
        }
        //将resp 中的要素按照http中应答的格式进行组装,利用stringstream
        //版本 状态码 状态码描述 \r\n
        std::stringstream resp_str;
        resp_str << req._version << " " << std::to_string(resp._statu) << " " << Util::StatuDesc(resp._statu) << "\r\n";
        //填充kv值
        for(auto & head : resp._headers)
        {
            resp_str << head.first << ": " << head.second << "\r\n";
        }
        //空行
        resp_str << "\r\n";
        //正文
        resp_str << resp._body;
        //发送应答
        conn->Send(resp_str.str().c_str() ,resp_str.str().size());
    }
    //判断是否为静态资源请求
    bool IsFileHandler(const HttpRequest& req)
    {
        //必须设置了资源请求路径
        if(_basedir.empty())
        {
            return false;
        }
        //请求方法不为GET或者HEAD就直接返回
        if(req._method != "GET" && req._method != "Head")
        {
            return false;
        }
        //如果请求资源路径不是一个合法的路径也直接返回
        if(Util::VaildPath(req._path)==false)
        {
            return false;
        } 
        //走到了此处就是请求资源存在了；如果所请求的资源并不是文件而是目录，也返回false
        //特殊情况： / --> 访问的是首页信息 index.html
        //获取到完整的资源路径：web根目录 + 所请求的资源路径
        std::string req_path = _basedir + req._path;
        //特殊处理
        if(req._path=="/")
        {
            req_path += "index.html";
        }
        //判断req_path 是否为文件资源
        if(Util::IsRegular(req_path)==false)
        {
            return false;
        }
        return true;
    }
    //将静态资源文件中的数据读取出来，放在应答的正文当中，并且设置mime
    void FileHandler(const HttpRequest& req, HttpResponce* resp)//静态资源处理
    {
        std::string req_path = _basedir + req._path;//请求资源路径
        //将路劲进行拆分
        if(req._path.back() == '/') //请求首页资源
        {
            req_path += "index.html";
        }
        //读取所要访问资源文件中的数据
        bool ret = Util::ReadFile(req_path ,&resp->_body);
        if(ret == false)
        {
            return;
        }
        //获取资源成功，设置mime
        std::string mime = Util::ExtMine(req_path);//根据请求资源路径获取mime
        resp->SetHeader("Content-Type" , mime);
    }
    void Dispatcher(const HttpRequest& req, HttpResponce* resp, Handlers &handlers)//功能性请求的分类处理
    {
        //判断请求的资源是否存在，存在则直接读取，没有则返回404；
        //利用正则表达式
        for(auto & handler : handlers)
        {
            //获取正则表达式
            const std::regex& re = handler.first;
            const Handler& functor = handler.second;
            //正则匹配
            bool ret = std::regex_match(req._path, req._matches , re);
            if(ret == false) continue;
            //匹配成功就取执行其所对应的函数
            return functor(req, resp);
        }
        resp->_statu = 400;//没有找到资源
    }
    void Route(const HttpRequest& req, HttpResponce* resp)//路由功能
    {
        //对请求进行分辨,进行路由;先默认为静态资源请求，不是静态的那么就是功能性资源请求，没有找到就返回404
        if(IsFileHandler(req) == true)
        {
            return FileHandler(req, resp);
        }

        //功能，判断请求方法是什么
        if(req._method =="GET" || req._method == "HEAD")
        {
            return Dispatcher(req ,resp ,_get_route);
        }
        else if(req._method == "POST")
        {
            return Dispatcher(req, resp ,_post_route);
        }
        else if(req._method == "PUT")
        {
            return Dispatcher(req, resp ,_put_route);
        }
        else if(req._method =="DELETE")
        {
            return Dispatcher(req, resp ,_delete_route);
        }
        //走到这里都没有返回就是没有找到资源
        resp->_statu = 405;
        return;
    }
    void OnConnected(const PtrConnection& conn)//设置上下文
    {
        conn->SetContext(HttpContext());
        DBG_LOG("new connection %p" , conn.get());
    } 
    void OnMessage(const PtrConnection& conn , Buffer* buffer)//缓冲区数据解析 + 处理
    {
        //buffer 当中不一定只有一个完整的请求待处理，所以此处需要写成循环
        while(buffer->ReadAbleSize() > 0)
        {
            //获取上下文
            HttpContext* context = conn->GetContext()->get<HttpContext>();
            //如果获取请求的过程中出错了，直接返回；只有当获得到了完整的请求才去处理这个请求
            context->RecvHttpRequest(buffer);//获取请求
            HttpRequest & req = context->Request();//获取请求
            //构建应答，并应答的状态码进行初始化
            HttpResponce resp(context->RespStatu());
            //判断其状态码
            if(context->RespStatu() >= 400)//客户端错误
            {
                //进行错误响应并关闭连接
                ErrorHandler(req, &resp);
                //写
                WriteResponce(conn, req, resp);
                //进行清理
                context->ReSet();
                buffer->MoveReadOffset(buffer->ReadAbleSize());
                conn->Shutdown();
                return;
            }
            //请求不完整就等待数据到来
            if(context->RecvStatu() != RECV_HTTP_OVER)
            {
                return;
            }
            //到了此处就是请求完整，可以进行路由
            Route(req, &resp);
            //构建应答
            WriteResponce(conn, req,resp);
            //根据请求的长短连接来确定此时是否需要关闭连接
            if(req.Close() == true) conn->Shutdown();
        }
    }
public:
    HttpServer(int port , int timeout = DEFALT_TIMEOUT):_server(port){
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected , this , std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage , this, std::placeholders::_1 , std::placeholders::_2));
    }
    ~HttpServer(){}
    void SetBaseDir(const std::string& path)//设置静态资源根目录
    {
        assert(Util::IsDirectory(path) == true);
        _basedir = path;
    }
    //四种请求方法:get post put delete
    void Get(const std::string& pathtern , const Handler & handler) 
    {
        _get_route.push_back(std::make_pair(std::regex(pathtern) , handler));
    }
    void Post(const std::string& pathtern , const Handler & handler)
    {
        _post_route.push_back(std::make_pair(std::regex(pathtern) , handler));
    }
    void Put(const std::string& pathtern , const Handler & handler)
    {
        _put_route.push_back(std::make_pair(std::regex(pathtern) , handler));
    }
    void Delete(const std::string& pathtern , const Handler & handler)
    {
        _delete_route.push_back(std::make_pair(std::regex(pathtern) , handler));
    }
    //设置线程数量
    void SetThreadCount(int count)
    {
        _server.SetThreadCount(count);
    }
    //启动连接不活跃就释放功能 --》默认启动，放在构造中
    void Listen()
    {
        _server.Start();
    }
}; 